import os

from django.shortcuts import render
from rest_framework.response import Response
from alipay import AliPay
from orders.models import OrderInfo
from django.conf import settings
# Create your views here.
from rest_framework.views import APIView


class PaymentView(APIView):

    def get(self, request, order_id):

        # 验证订单编号
        try:
            order = OrderInfo.objects.get(user=request.user, order_id=order_id, pay_method=2)
        except:
            raise Response({'error': '订单不存在'}, status=401)

        # 初始化操作
        # alipay = AliPay(
        #     appid=settings.ALIPAY_APPID,
        #     app_notify_url=None,  # 默认回调url
        #     app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
        #     alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),'keys/alipay_public_key.pem'),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
        #     sign_type="RSA2",  # RSA 或者 RSA2
        #     debug = settings.ALIPAY_DEBUG  # 默认False
        # )
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject='美多商城%s'%order_id,
            notify_url="https://www.meiduo.site:8080/pay_success.html"  # 可选, 不填则使用默认notify url
        )

        url = settings.ALIPAY_URL+order_string

        return Response({'alipay_url': url})

